#include "cypher.h"

cypherT
cypher(void *msg, int len, char *key)
{
	cypherT cypher;
	int i, cqty, end= 0;
	unsigned char *auxkey, *auxmsg;
	
	cypher.msg= NULL;
	cypher.len= 0;
	if( len <= 0 || (auxkey= calloc(8, 1)) == NULL )
		return cypher;
	
	if( (cypher.msg= malloc(len+(8-len%8))) == NULL )
	{
		free(auxkey);
		return cypher;
	}
	if( (auxmsg= calloc(8, 1)) == NULL )
	{
		free(auxkey);
		free(cypher.msg);
		return cypher;
	}
	
	for(i= 0; i<8 && !end; i++)
	{
		auxkey[i]= key[i];
		if( key[i] == '\0' )
			end= 1;
	}
	cypher.len= len+(8-len%8);
	cqty= floor(len/8.0);
	/* cypher message */
	for(i=0; i<cqty; i++)
		des_encipher((unsigned char *)msg+(i*8), 
			(unsigned char *)cypher.msg+(i*8), auxkey);
	
	strncpy((char *)auxmsg, (char *)msg+(i*8), len-(cqty*8));
	des_encipher(auxmsg, cypher.msg+(i*8), auxkey);
	
	free(auxmsg);
	free(auxkey);
	return cypher;
}

cypherT
decypher(void *msg, int len, char *key)
{
	cypherT cypher;
	int i, cqty, end= 0;
	unsigned char *auxkey;
	
	cypher.msg= NULL;
	cypher.len= 0;
	if( len <= 0 || (auxkey= calloc(8, 1)) == NULL )
		return cypher;
	
	if( (cypher.msg= malloc(len)) == NULL )
	{
		free(auxkey);
		return cypher;
	}
	
	for(i= 0; i<8 && !end; i++)
	{
		auxkey[i]= key[i];
		if( key[i] == '\0' )
			end= 1;
	}
	cypher.len= len;
	cqty= len/8;
	/* decypher message */
	for(i=0; i<cqty; i++)
		des_decipher((unsigned char *)msg+(i*8), 
				(unsigned char *)cypher.msg+(i*8), auxkey);
	
	free(auxkey);
	return cypher;
}

/* a wrapper for cypher */
int
cypher2(char * string, int len, char * key)
{
	cypherT cyphered;
	
	if(string == NULL)
		return -1;
	
	cyphered = cypher(string, len, key);
	
	if(cyphered.msg == NULL)
		return -1;
	
	memcpy(string, cyphered.msg, cyphered.len);
	free(cyphered.msg);
	return 1;
}

/* a wrapper for decypher */
int
decypher2(char * string, int len, char * key)
{
	cypherT decyphered;
	
	if (string == NULL)
		return NOT_OK;
	
	decyphered = decypher(string, len, key);
	
	if (decyphered.msg == NULL)
		return NOT_OK;
	
	memcpy(string, decyphered.msg, decyphered.len);
	
	free(decyphered.msg);
	return OK;
}
